import glob
import logging
import os
import re
import shlex
import shutil
import subprocess
from pathlib import Path

import toml

Logger = logging.getLogger(__name__)
FORMAT = "%(asctime)s %(lineno)d %(message)s"
logging.basicConfig(format=FORMAT)
Logger.setLevel(logging.DEBUG)


def avaliable_terms(terms):
    """
    获取当前系统中可用的终端名称
    """
    processes = {
        term:
        subprocess.Popen(
            shlex.split(f"command -v {term}"),
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
        )
        for term in terms
    }
    avaliable = []
    for k, p in processes.items():
        if p.returncode is None:
            output = p.stdout.read().decode("utf-8")
            Logger.debug(f"output = {output}")
            if len(output) > 0:
                avaliable.append(k)
            else:
                Logger.debug(f"{k} mesg is empty")
        else:
            Logger.error(f"Process failed")
    return avaliable


def path_for_config(paths):
    """
    transform env path to absolute path
    """
    p = re.compile("\${?([a-zA-Z0-9]+)}?")
    r = re.findall(p, paths)
    for i in r:
        if i in os.environ:
            e = os.environ[i]
            paths = re.sub(p, e, paths)
    return paths


class Config_for_tools(object):

    def __init__(self, config_file, config=None):
        self.config = toml.load(config_file)
        self.config_path = Path(__file__).parent if config is None else config

    def check_and_config(config, name):
        pass

    def joshuto_config(self):
        """
        set config for joshuto
        """
        assert "software" in config, "software field must be in config"
        c_config = config["software"]
        assert ("joshuto" in c_config
                ), f"configure for joshuto,but now joshoto not in {c_config}"
        cfg = c_config["joshuto"]
        __import__("pdb").set_trace()
        terms = avaliable_terms(cfg["terms"])
        dst = path_for_config(cfg["dst"])
        joshuto_config = self.config_path.joinpath("joshuto")

        joshuto_config.mkdir(exist_ok=True)
        [
            shutil.copy(file, dst) for file in glob.glob(f"{joshuto_config}/*")
            if not os.path.isdir(file)
        ]
        if cfg["select"] == "kitty":
            [
                shutil.copy(file, dst)
                for file in glob.glob(f"{joshuto_config.joinpath('kitty')}/*")
                if not os.path.isdir(file)
            ]
            Logger.debug("Copy configure file for kitty")
        else:
            [
                shutil.copy(file, dst) for file in glob.glob(
                    f"{joshuto_config.joinpath('default')}/*")
                if not os.path.isdir(file)
            ]
            Logger.debug("Copy config for others")
        Logger.debug(f"Copy {joshuto_config} to {dst}")

    def kitty_config(self, config, kitty_path):
        for conf in glob.glob(f"{config}/*.conf"):
            Logger.debug(f"Copy {conf} to {kitty_path}")
            shutil.copy(conf, kitty_path)


if __name__ == "__main__":
    config_file = Path(__file__).parent.joinpath("config.toml")
    config = toml.load(config_file)
    # terms = avaliable_terms(['kitty','iterm2'])
    tools = Config_for_tools(config_file)
    tools.joshuto_config()
